package com.model;

import java.util.*;

import com.controller.*;



public class Packet {
	private PacketHeader header;
	private byte[] stream;

	public Packet() {
		super();
	}

	public Packet(PacketHeader header) {
		super();
		this.header = header;
	}
	
	public Packet(PacketHeader header, byte[] encodedData) {
		byte[] encodedHeader, encodedPacket;
		Codec coder = new Codec();

		this.header = header;
		encodedHeader = coder.encodePacketHeader(header);
		encodedPacket = new byte[encodedHeader.length + encodedData.length];

		System.arraycopy(encodedHeader, 0, encodedPacket, 0,
				encodedHeader.length);
		System.arraycopy(encodedData, 0, encodedPacket, encodedHeader.length,
				encodedData.length);
		stream = encodedPacket;
	}

	public Packet(byte[] packetStream) {
		super();
		this.stream = packetStream.clone();
	}

	public PacketHeader getHeader() {
		Codec coder = new Codec();
		if (header != null)
			return header;
		header = coder.decodePacketHeader(stream);
		return header;
	}

	public void setHeader(PacketHeader header) {
		this.header = header;
	}

	public byte[] getData() {
		PacketHeader head = getHeader();
		if (stream != null)
			return Arrays.copyOfRange(stream, PacketHeader.HEADER_SIZE,
					PacketHeader.HEADER_SIZE + head.getDataLength());
		else
			return null;
	}

	public byte[] getBytes() {
		if (stream != null)
			return stream.clone();
		return null;
	}
}